<template>
  <div class="app-container">
    <!-- 加载状态 -->
    <el-skeleton :loading="loading" animated>
      <template slot="template">
        <el-skeleton-item variant="image" style="width: 100%; height: 300px;" />
        <div style="padding: 14px;">
          <el-skeleton-item variant="h3" style="width: 50%" />
          <el-skeleton-item variant="text" style="width: 100%" />
          <el-skeleton-item variant="text" style="width: 100%" />
        </div>
      </template>

      <template>
        <!-- 酒店基本信息 -->
        <el-card class="box-card hotel-info" shadow="hover">
          <div slot="header" class="card-header">
            <span class="header-title">酒店信息</span>
            <div class="header-rating" v-if="isLogin">
              <el-button type="text" @click="handleCollect">收藏</el-button>
            </div>
          </div>
          <el-row :gutter="30">
            <el-col :span="8">
              <div class="hotel-image-container">
                <el-image class="hotel-image" :src="hotelInfo.image" fit="cover">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </el-col>
            <el-col :span="16">
              <div class="hotel-details">
                <h2 class="hotel-name">{{ hotelInfo.name }}</h2>
                <div class="hotel-meta">
                  <div class="meta-item">
                    <i class="el-icon-location"></i>
                    <span>{{ hotelInfo.address }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-phone"></i>
                    <span>{{ hotelInfo.phone }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-location"></i>
                    <span>{{ hotelInfo.address }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-star-on"></i>
                    <el-rate v-model="hotelInfo.starLevel" disabled text-color="#ff9900" />
                  </div>
                </div>
                <div class="hotel-features">
                  <div class="feature-item">
                    <el-tag type="success" v-for="(feature, index) in hotelInfo.features" :key="index"
                      style="margin-right: 10px;">{{ feature }}</el-tag>
                  </div>
                </div>
                <div class="hotel-description">
                  <p>{{ hotelInfo.introduce }}</p>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 房型列表 -->
        <el-card class="box-card room-list" shadow="hover">
          <div slot="header" class="card-header">
            <span class="header-title">房型列表</span>
          </div>
          <el-table :data="roomList">
            <el-table-column label="房型" align="center" prop="name" />
            <el-table-column label="面积/㎡" align="center" prop="area">
            </el-table-column>
            <el-table-column label="人数/间" align="center" prop="peopleNumber">
            </el-table-column>
            <el-table-column label="价格/晚" align="center" prop="price">
            </el-table-column>
            <el-table-column label="总数量" align="center" prop="number">
            </el-table-column>
            <el-table-column label="剩余数量" align="center" prop="remainNumber"></el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="primary" size="medium" @click="handleBook(scope.row)" :disabled="!isLogin">预定</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 评论列表 -->
        <el-card class="box-card comment-list" shadow="hover">
          <div slot="header" class="card-header">
            <span class="header-title">用户评价</span>
            <el-button @click="handleAddComment" v-if="isLogin">
              写评价
            </el-button>
          </div>
          <div v-if="comments == null || comments.length === 0" class="empty-comment">
            <el-empty description="暂无评价"></el-empty>
          </div>
          <div v-for="(comment, index) in comments" :key="index" class="comment-item">
            <div class="comment-header">
              <div class="user-info">
                <el-avatar :size="40" :src="comment.avatar"></el-avatar>
                <div class="user-details">
                  <span class="user-name">{{ comment.nickname }}</span>
                </div>
              </div>
              <div>
                <span class="comment-time">{{ comment.createTime }}</span>
                <el-rate v-model="comment.score" disabled show-score text-color="#ff9900">
                </el-rate>
              </div>
            </div>
            <div class="comment-content">
              <p class="comment-text">{{ comment.content }}</p>
              <div class="comment-footer">
                <div class="comment-actions">
                  <!-- <span class="action-item">
                    <i class="el-icon-thumb"></i>
                    <span>{{ comment.likes }}</span>
                  </span> -->
                  <span class="action-item">
                    <i class="el-icon-chat-dot-round" @click="replyComment(comment.id)"></i>
                    <span>{{ comment.replies }}</span>
                  </span>
                </div>
              </div>
            </div>
            <div v-for="(reply, cindex) in comment.childList" :key="cindex" class="child-comment">
              <div class="comment-header">
                <div class="user-info">
                  <el-avatar :size="40" :src="reply.avatar"></el-avatar>
                  <div class="user-details">
                    <span class="user-name">{{ reply.nickname }}</span>
                    <span style="margin: 0 10px;">回复</span>
                    <span>{{ reply.replyNickname }}</span>
                  </div>
                </div>
                <div>
                  <span class="comment-time">{{ reply.createTime }}</span>
                </div>
              </div>
              <div class="comment-content">
                <p class="comment-text">{{ reply.content }}</p>
                <div class="comment-footer">
                  <div class="comment-actions">
                    <!-- <span class="action-item">
                    <i class="el-icon-thumb"></i>
                    <span>{{ comment.likes }}</span>
                  </span> -->
                    <span class="action-item">
                      <i class="el-icon-chat-dot-round" @click="replyComment(comment.id)"></i>
                      <span>{{ comment.replies }}</span>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="pagination-container">
            <el-pagination @size-change="handleCommentSizeChange" @current-change="handleCommentCurrentChange"
              :current-page="commentPageNum" :page-size="commentPageSize" layout="prev, pager, next"
              :total="commentTotal">
            </el-pagination>
          </div>
        </el-card>
      </template>
    </el-skeleton>

    <!-- 预订对话框 -->
    <el-dialog title="房间预订" :visible.sync="bookDialogVisible" width="50%" custom-class="book-dialog">
      <el-form :model="bookForm" :rules="bookRules" ref="bookForm" label-width="100px">
        <el-form-item label="入住日期" prop="inDate">
          <el-date-picker v-model="bookForm.inDate" type="date" placeholder="选择入住日期"
            :picker-options="pickerOptions" @change="calculateTotalAmount">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="离店日期" prop="outDate">
          <el-date-picker v-model="bookForm.outDate" type="date" placeholder="选择离店日期"
            :picker-options="pickerOptions" @change="calculateTotalAmount">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预定数量" prop="roomCount">
          <el-input-number v-model="bookForm.roomCount" :min="1" controls-position="right" @change="calculateTotalAmount">
          </el-input-number>
        </el-form-item>
        <el-form-item label="特殊要求" prop="remark">
          <el-input type="textarea" v-model="bookForm.remark" :rows="3" placeholder="请输入您的特殊要求（选填）">
          </el-input>
        </el-form-item>
        <el-form-item label="总金额">
          <span class="total-amount">¥{{ totalAmount }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bookDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitBook">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 评论对话框 -->
    <el-dialog title="发表评价" :visible.sync="commentDialogVisible" width="50%" custom-class="comment-dialog">
      <el-form :model="commentForm" :rules="commentRules" ref="commentForm" label-width="100px">
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="commentForm.score" show-score text-color="#ff9900">
          </el-rate>
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input type="textarea" v-model="commentForm.content" :rows="4" placeholder="请输入您的评价内容">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="commentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitComment">发 表</el-button>
      </div>
    </el-dialog>
    <el-dialog title="回复评价" :visible.sync="replyCommentVisible" width="50%" custom-class="comment-dialog">
      <el-form :model="commentForm" :rules="commentRules" ref="commentForm" label-width="100px">
        <el-form-item label="评价内容" prop="content">
          <el-input type="textarea" v-model="commentForm.content" :rows="4" placeholder="请输入您的评价内容">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="replyCommentVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitComment">发 表</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCommentList, getHotelDetailsList, getFeaturesList, getCommentSubmit, getCollectAdd, getOrderAdd } from "@/api";

export default {
  name: 'HotelDetails',
  data() {
    return {
      loading: true,
      roomLoading: false,
      searchQuery: '',
      featuresList: [],
      hotelInfo: {
        hotelName: '',
        address: '',
        phone: '',
        starLevel: '',
        description: '',
        hotelImage: '',
        tags: [],
        features: [],
        rating: 4.5
      },
      roomList: [],
      filteredRoomList: [],
      comments: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      commentPageNum: 1,
      commentPageSize: 5,
      commentTotal: 0,
      bookDialogVisible: false,
      isLogin: false,
      currentRoom: null,
      totalAmount: 0,
      bookForm: {
        inDate: null,
        outDate: null,
        roomCount: null,
        remark: null
      },
      bookRules: {
        inDate: [
          { required: true, message: '请选择入住日期', trigger: 'change' }
        ],
        outDate: [
          { required: true, message: '请选择离店日期', trigger: 'change' }
        ],
        roomCount: [
          { required: true, message: '请选择预定数量', trigger: 'change' }
        ],
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      commentDialogVisible: false,
      replyCommentVisible: false,
      commentForm: {
        score: 0,
        content: null,
        hotelId: this.$route.query.hotelId,
        pId: null,
      },
      commentRules: {
        score: [
          { required: true, message: '请选择评分', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入评价内容', trigger: 'blur' },
          { min: 5, max: 500, message: '评价内容长度在 5 到 500 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    searchQuery(val) {
      this.filterRooms(val)
    }
  },
  created() {
    this.isLogin = localStorage.getItem('userInfo') != null ? true : false
    this.getHotelInfo()
    this.getRoomList()
    this.getComments()
  },
  methods: {
    handleCollect() {
      getCollectAdd({
        hotelId: this.$route.query.hotelId,
      }).then(res => {
        this.$message.success('收藏成功')
      }).catch(err => {
      })
    },
    replyComment(id) {
      this.commentForm = {
        pId: id,
        score: 0,
        content: null,
        hotelId: this.$route.query.hotelId,
      }
      this.replyCommentVisible = true
    },
    handleAddComment() {
      this.commentForm = {
        score: 0,
        content: null,
        hotelId: this.$route.query.hotelId,
      }
      this.commentDialogVisible = true
    },
    async submitComment() {
      try {
        await this.$refs.commentForm.validate()
        getCommentSubmit(this.commentForm).then(resp => {
          this.$message.success('评价发表成功')
          this.commentDialogVisible = false
          this.replyCommentVisible = false
          this.getComments() // 刷新评论列表
        }).catch(err => {
        })
      } catch (error) {

      }
    },
    async getHotelInfo() {
      try {
        this.loading = true
        await getFeaturesList({
          pageSize: 100
        }).then(response => {
          this.featuresList = response.rows;
        }).catch(err => {
        });

        getHotelDetailsList(this.$route.query.hotelId).then(response => {
          this.hotelInfo = response.data.hotel;
          this.roomList = response.data.rooms;
          if (this.hotelInfo.features && this.hotelInfo.features.length) {
            this.hotelInfo.features = this.hotelInfo.features.map(featureId => {
              const feature = this.featuresList.find(item => item.featuresId === featureId);
              return feature ? feature.name : '';
            }).filter(Boolean);
          }
        })
      } catch (error) {
      } finally {
        this.loading = false
      }
    },
    async getRoomList() {
      try {
        this.roomLoading = true
        // TODO: 调用API获取房型列表
        // const response = await getRoomList({
        //   hotelId: this.$route.params.id,
        //   pageNum: this.pageNum,
        //   pageSize: this.pageSize
        // })
        // this.roomList = response.data.list
        // this.total = response.data.total
      } catch (error) {
        this.$message.error('获取房型列表失败')
      } finally {
        this.roomLoading = false
      }
    },
    async getComments() {
      try {
        getCommentList({
          hotelId: this.$route.query.hotelId,
          pageNum: this.commentPageNum,
          pageSize: this.commentPageSize
        }).then(resp => {
          this.comments = resp.rows
          this.commentTotal = resp.total
        })
      } catch (error) {
        this.$message.error('获取评论列表失败')
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getRoomList()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.getRoomList()
    },
    handleCommentSizeChange(val) {
      this.commentPageSize = val
      this.getComments()
    },
    handleCommentCurrentChange(val) {
      this.commentPageNum = val
      this.getComments()
    },
    handleFilter() {
      // TODO: 实现房型筛选功能
    },
    handleBook(row) {
      this.currentRoom = row;
      this.bookForm = {
        inDate: null,
        outDate: null,
        roomCount: 1,
        remark: null
      }
      this.totalAmount = 0;
      this.bookDialogVisible = true
    },
    async submitBook() {
      try {
        await this.$refs.bookForm.validate()
        getOrderAdd({
          hotelId: this.$route.query.hotelId,
          hotelRoomType: this.currentRoom.type,
          inDate: this.bookForm.inDate,
          outDate: this.bookForm.outDate,
          roomCount: this.bookForm.roomCount,
          remark: this.bookForm.remark,
          totalAmount: this.totalAmount,
        }).then(resp => {
          this.$message.success('预订成功')
          this.bookDialogVisible = false
        }).catch(err => {
        })
      } catch (error) {
        if (error.message) {
          this.$message.error(error.message)
        }
      }
    },
    getTagType(index) {
      const types = ['', 'success', 'warning', 'danger', 'info']
      return types[index % types.length]
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 0) {
        return 'even-row'
      }
      return 'odd-row'
    },
    filterRooms(query) {
      if (!query) {
        this.filteredRoomList = this.roomList
        return
      }
      this.filteredRoomList = this.roomList.filter(room =>
        room.roomType.toLowerCase().includes(query.toLowerCase())
      )
    },
    viewMoreImages() {
      // TODO: 实现查看更多图片功能
    },
    calculateTotalAmount() {
      if (!this.currentRoom || !this.bookForm.inDate || !this.bookForm.outDate) {
        this.totalAmount = 0;
        return;
      }
      const checkIn = new Date(this.bookForm.inDate);
      const checkOut = new Date(this.bookForm.outDate);
      if (checkIn >= checkOut) {
        this.totalAmount = 0;
        return;
      }
      const days = Math.ceil((checkOut - checkIn) / (1000 * 60 * 60 * 24));
      this.totalAmount = this.currentRoom.price * days * this.bookForm.roomCount;
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.box-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
}


.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.hotel-info {
  margin-top: 20px;
}

.hotel-image-container {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
}

.hotel-image {
  width: 100%;
  height: 300px;
  transition: all 0.3s;
}

.image-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  text-align: center;
  opacity: 0;
  transition: all 0.3s;
}

.hotel-image-container:hover .image-overlay {
  opacity: 1;
}

.hotel-details {
  padding: 0 20px;
}

.hotel-name {
  font-size: 24px;
  color: #303133;
  margin-bottom: 20px;
}

.hotel-meta {
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  color: #606266;
}

.meta-item i {
  margin-right: 10px;
  color: #409EFF;
}

.hotel-description {
  margin-bottom: 20px;
  color: #606266;
  line-height: 1.6;
}

.hotel-features {
  margin-bottom: 20px;
}

.features-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.feature-item {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.feature-item i {
  margin-right: 5px;
  color: #409EFF;
}

.hotel-tags {
  margin-top: 20px;
}

.tag-item {
  margin-right: 10px;
  margin-bottom: 10px;
  border-radius: 15px;
}

.room-type {
  display: flex;
  align-items: center;
}

.room-image {
  width: 120px;
  height: 80px;
  border-radius: 4px;
  margin-right: 15px;
}

.room-info {
  flex: 1;
}

.room-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.room-features {
  display: flex;
  gap: 5px;
}

.price-container {
  display: flex;
  align-items: baseline;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.price-unit {
  color: #909399;
  font-size: 12px;
  margin-left: 2px;
}

.area-info,
.bed-info {
  display: flex;
  align-items: center;
  color: #606266;
}

.area-info i,
.bed-info i {
  margin-right: 5px;
  color: #409EFF;
}

.comment-item {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  transition: all 0.3s;
}

.comment-item:hover {
  background-color: #f5f7fa;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 10px;
}

.user-name {
  font-weight: bold;
  color: #303133;
}

.user-level {
  font-size: 12px;
  color: #909399;
  margin-left: 5px;
}

.comment-time {
  color: #909399;
  font-size: 12px;
}

.comment-text {
  margin: 10px 0;
  color: #606266;
  line-height: 1.6;
}

.comment-images {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.comment-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  cursor: pointer;
}

.comment-footer {
  margin-top: 10px;
}

.comment-actions {
  display: flex;
  gap: 15px;
  justify-content: right;
}

.action-item {
  display: flex;
  align-items: center;
  color: #909399;
  cursor: pointer;
  transition: color 0.3s;
}

.action-item:hover {
  color: #409EFF;
}

.action-item i {
  margin-right: 5px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.empty-comment {
  padding: 40px 0;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.book-dialog {
  border-radius: 8px;
}

.book-dialog .el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.book-dialog .el-dialog__body {
  padding: 30px 20px;
}

.book-dialog .el-dialog__footer {
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

::v-deep .even-row {
  background-color: #fafafa;
}

::v-deep .odd-row {
  background-color: #fff;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.child-comment {
  padding-left: 30px;
}

.total-amount {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
}
</style>